<?php
// This controller handles the logic for the login page

class SiteController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		if (Yii::app()->user->isGuest)
			$this->redirect(Yii::app()->request->baseUrl . '/site/login');
		else {
			$this->getLandingPage();
		}
	}

	/**
	 * Displays login page and handles login business logic
	 */
	public function actionLogin()
	{
		$model=new Users;
		$model->scenario='login';
		
		if (Yii::app()->user->isGuest) {
			
			if (isset($_POST['Users'])) {
				$model->user_name = $_POST['Users']['user_name'];
				$model->password = $_POST['Users']['password'];
				$model->user_type_ID = $_POST['Users']['user_type_ID'];
				
				if ($model->validate()) {					
					$identity = new UserIdentity($model->user_name, $model->password);
					Yii::app()->user->setState('userTypeID', $model->user_type_ID);
					if ($identity->authenticate()) {
						Yii::app()->user->login($identity);
						//$this->redirect(Yii::app()->user->returnUrl);
						
						// Redirects to appropriate landing pages
						$this->getLandingPage();
					}
					else
						echo 'Login Not Successful: ' . $identity->errorMessage . '<br />';
				}
			}
		}
		
		$this->render('login',array('model'=>$model));
	}
	
	public function getLandingPage() 
	{		
		if (Yii::app()->user->userType=='b')
			$this->redirect(Yii::app()->request->baseUrl . '/landing/buyer');
		else if (Yii::app()->user->userType=='s')
			$this->redirect(Yii::app()->request->baseUrl . '/landing/supplier');
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
}